package com.qihunet.tplus.productimport.utils;

import com.qihunet.tplus.productimport.Service.BaseDataService;
import com.qihunet.tplus.productimport.entity.CostAllocationOrderDetails;
import com.qihunet.tplus.productimport.entity.InventoryEntityDTO;
import com.qihunet.tplus.productimport.entity.UnitDTO;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Predicate;

@Component
public class ExcelComponent {
    @Autowired
    private BaseDataService baseDataService;

    public  Map uploadFileDataToDB(File file, String excelType) throws FileNotFoundException {
        Map<String,Object> excelMap=new HashMap<>();
        excelMap.put("filePath",file.getAbsolutePath());
        Map<String,Object> resultMap=getExcelData(excelMap,file,excelType);
        ResultInfo<CostAllocationOrderDetails> resultInfo= (ResultInfo<CostAllocationOrderDetails>) resultMap.get("resultInfo");

        if(resultInfo.getResultCode()==ResultCode.SUCCESS){
            excelMap.put("orderData",resultInfo.getDataList());
            excelMap.put("date",resultMap.get("date"));
            excelMap.put("code",resultMap.get("code"));
            excelMap.put("result",true);
        }else{
            excelMap.put("result",false);
            excelMap.put("message",resultInfo.getErrorMessage());
        }
        return excelMap;
    }

    /**
     * 获取订单EXCEL数据
     * @param excelMap
     * @param file
     * @param excelType
     * @return
     * @throws FileNotFoundException
     */
    private  Map getExcelData(Map<String, Object> excelMap, File file, String excelType) throws FileNotFoundException {
        Map<String,Object> resultMap=new HashMap<>();

        ResultInfo<CostAllocationOrderDetails> resultInfo=new ResultInfo<>();
        resultInfo.setResultCode(ResultCode.ERROR);
        //商品信息
        List<InventoryEntityDTO> goodsInfoList=baseDataService.findAllGoodsInfo();
        //单位信息
        List<UnitDTO> unitInfoList=baseDataService.findAllUnitInfo();

        InputStream inputStream=new FileInputStream(file);

        Integer flagRow=0;
        Integer flagCell=0;
        Workbook workBook = null;
        try {

            if (!excelType.equals("XLSX")) {
                workBook = new HSSFWorkbook(inputStream);
            } else {
                workBook = new XSSFWorkbook(inputStream);
            }
            // 在Excel文档中，第一张工作表的缺省索引是0
            // 其语句为：HSSFSheet sheet = workbook.getSheetAt(0);?
            Sheet sheet = workBook.getSheet("sheet1");
            if (sheet == null) {
                resultInfo.setErrorMessage("excel中不存在名称为【sheet1】的标签页");
                resultMap.put("resultInfo",resultInfo);
                return resultMap;
            }
            // 获取到Excel文件中的所有行数
            int rows = sheet.getPhysicalNumberOfRows();
            //1、读取单号
            Cell importCodeCell= sheet.getRow(2).getCell(1);
            resultMap.put("code",importCodeCell.getStringCellValue());
            //2.读取日期
            Cell importDJDateCell= sheet.getRow(1).getCell(1);
            String orderDate=importDJDateCell.getStringCellValue();
            SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyy-MM-dd");
            resultMap.put("date",simpleDateFormat.parse(orderDate));

            //创建客户订单
            int titleCellCount = sheet.getRow(3).getLastCellNum();
            Map<Integer,String> customerMap=new HashMap<>();
            List<CostAllocationOrderDetails> costAllocationOrderDetailsList=new ArrayList<>();

            for(Integer i=0;i<titleCellCount;i++){
                // 获取到列的值
                final Cell cell =  sheet.getRow(3).getCell(i);
                if (cell != null) {
                    customerMap.put(i,cell.getStringCellValue());
                }
            }


            // 遍历行,默认从第0行开始
            for (int i = 4; i <= rows; i++) {
                flagRow=i;
                // 读取左上端单元格
                Row row = sheet.getRow(i);
                // 行不为空
                if (row != null) {
                    // 获取到Excel文件中的所有的列
                    int cells = row.getLastCellNum();
                    CostAllocationOrderDetails costAllocationOrderDetails=new CostAllocationOrderDetails();
                    // 遍历列
                    for (int j = 0; j <= cells; j++) {
                        flagCell=j;
                        // 获取到列的值
                        final Cell cell = row.getCell(j);
                        if (cell != null) {
                            switch (customerMap.get(j)) {
                                case "加工单号":
                                    costAllocationOrderDetails.setJgdcode(cell.getStringCellValue());
                                    break;
                                case "产品编码":
                                    final String goodsCode=cell.getStringCellValue();
                                    InventoryEntityDTO inventoryEntityDTOTemp= goodsInfoList.stream().filter(new Predicate<InventoryEntityDTO>() {
                                        @Override
                                        public boolean test(InventoryEntityDTO inventoryEntityDTO) {
                                            return inventoryEntityDTO.getCode().equals(goodsCode);
                                        }
                                    }).findFirst().get();
                                    if(inventoryEntityDTOTemp==null){
                                        throw new RuntimeException("产品编码：【"+cell.getStringCellValue()+"】未找到,错误坐标：第"+flagRow+"行，第"+flagCell+"列");
                                    }
                                    costAllocationOrderDetails.setIdinventory(inventoryEntityDTOTemp.getId());

                                    break;
                                case "主单位":
                                    final String unitName=cell.getStringCellValue();
                                    UnitDTO unitDTOTemp= unitInfoList.stream().filter(new Predicate<UnitDTO>() {
                                        @Override
                                        public boolean test(UnitDTO unitDTO) {
                                            return unitDTO.getName().equals(unitName);
                                        }
                                    }).findFirst().get();
                                    if(unitDTOTemp==null){
                                        throw new RuntimeException("主单位：【"+cell.getStringCellValue()+"】未找到,错误坐标：第"+flagRow+"行，第"+flagCell+"列");
                                    }
                                    costAllocationOrderDetails.setIdbaseunit(unitDTOTemp.getId());
                                    break;
                                case "入库数量":
                                    costAllocationOrderDetails.setQuantity(new BigDecimal(cell.getNumericCellValue()));
                                    break;
                                case "直接材料":
                                    costAllocationOrderDetails.setDirectmaterials(new BigDecimal(cell.getNumericCellValue()));
                                    break;
                                case "间接材料":
                                    costAllocationOrderDetails.setIndirectmaterials(new BigDecimal(cell.getNumericCellValue()));
                                    break;
                                case "制造费用":
                                    costAllocationOrderDetails.setManufacturecost(new BigDecimal(cell.getNumericCellValue()));

                                    break;
                                case "人工费用":
                                    costAllocationOrderDetails.setMancost(new BigDecimal(cell.getNumericCellValue()));

                                    break;
                                case "其他费用":
                                    costAllocationOrderDetails.setOthercost(new BigDecimal(cell.getNumericCellValue()));

                                    break;
                                case "总成本":
                                    costAllocationOrderDetails.setTotalcost(new BigDecimal(cell.getNumericCellValue()));

                                    break;
                                case "单位成本":
                                    costAllocationOrderDetails.setUnitcost(new BigDecimal(cell.getNumericCellValue()));
                                    break;
                            }
                        }
                    }
                    costAllocationOrderDetailsList.add(costAllocationOrderDetails);
                }
            }
            resultInfo.setDataList(costAllocationOrderDetailsList);
            resultInfo.setResultCode(ResultCode.SUCCESS);
        } catch (Exception ex) {
            resultInfo.setErrorMessage(ex.getMessage());
            ex.printStackTrace();
        }
        resultMap.put("resultInfo",resultInfo);
        return resultMap;

    }
}
